package com.sy.olddriver.model;

import com.alibaba.fastjson.JSON;
import com.sun.javafx.scene.control.skin.TableHeaderRow;
import com.sy.olddriver.annotation.Controller;
import com.sy.olddriver.annotation.RequestMapping;
import com.sy.olddriver.annotation.ResponseBody;
import com.sy.olddriver.constant.AppConstant;
import com.sy.olddriver.dao.OrderDao;
import com.sy.olddriver.dao.impl.OrderDaoImpl;
import com.sy.olddriver.dto.OrderItemBaseInfo;
import com.sy.olddriver.entity.Order;
import com.sy.olddriver.entity.User;
import com.sy.olddriver.exception.BusinessException;
import com.sy.olddriver.service.UserService;
import com.sy.olddriver.service.impl.UserServiceImpl;
import com.sy.olddriver.utils.CookieUtils;
import com.sy.olddriver.utils.DBUtils;
import com.sy.olddriver.utils.RedisUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("order")
public class OrderModel {
    private UserService userService = new UserServiceImpl();
    private OrderDao orderDao = new OrderDaoImpl();

    @RequestMapping("generate")
    @ResponseBody
    public String generateOrder(HttpServletRequest req) {
        String orderItemBaseInfoStr = req.getParameter("items");
        List<OrderItemBaseInfo> orderItemBaseInfoList = JSON.parseArray(orderItemBaseInfoStr, OrderItemBaseInfo.class);
        List<String> cartDelPidList = new ArrayList<>();
        String oid = RedisUtils.generateOid();
        try {
            DBUtils.beginTx();
            User user = userService.getLoginUser(CookieUtils.getCookie(AppConstant.COOKIE_USER_TOKEN_NAME, req));
            //插入订单表记录
            orderDao.insertOrder(oid, user.getId());
            //插入订单商品表记录
            for (OrderItemBaseInfo itemBaseInfo : orderItemBaseInfoList) {
                orderDao.insertOrderItem(user.getId(), itemBaseInfo.getPid(), oid, itemBaseInfo.getCount());
                cartDelPidList.add(String.valueOf(itemBaseInfo.getPid()));
            }
            DBUtils.endTx();
            //清除购物车中对应的商品信息
            String[] pids = cartDelPidList.toArray(new String[cartDelPidList.size()]);
            RedisUtils.hdel(AppConstant.REDIS_USER_CART_KEY_PREFIX + user.getId(), pids);
        } catch (Exception e) {
            e.printStackTrace();
            DBUtils.rollBack();
            throw new BusinessException(e);
        }
        return oid;
    }

}
